<template>
  <div style="height:100%">
    <el-row :gutter="20" style="margin-bottom: 20px">
      <el-col :span="5">
        <el-input v-model="searchId" placeholder="请输入ID"></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-col>
    </el-row>
    <div class="top-btns">
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </div>
    <el-table :data="students" style="width: 100%" height="calc(100% - 160px)">
      <el-table-column label="序号" width="70">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="grade" label="年级"></el-table-column>
      <el-table-column prop="phoneNumber" label="电话号码"></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total,sizes,prev,pager,next,jumper"
      :total="totalPages"
    ></el-pagination>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" label-width="100px" style="margin-right: 20px">
        <el-form-item label="姓名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.age"></el-input>
        </el-form-item>
        <el-form-item label="年级">
          <el-input v-model="form.grade"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="form.phoneNumber"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import http from "../../api";

export default {
  data() {
    return {
      searchId: "",
      searchAge: "",
      searchGrade: "",
      searchPhoneNumber: "",
      pageIndex: 1,
      pageSize: 10,
      totalPages: 0,
      students: [],
      form: {
        id: null,
        name: "",
        age: "",
        grade: "",
        phoneNumber: "",
      },
      dialogVisible: false,
      dialogTitle: "",
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    handleSearch() {
      this.pageIndex = 1;
      this.fetchData();
    },
    handleReset() {
      this.pageIndex = 1;
      this.searchId = "";
      this.searchAge = "";
      this.searchGrade = "";
      this.searchPhoneNumber = "";
      this.fetchData();
    },
    handleSizeChange(size) {
      this.pageIndex = 1;
      this.pageSize = size;
      this.fetchData();
    },
    handleCurrentChange(num) {
      this.pageIndex = num;
      this.fetchData();
    },
    async fetchData() {
      try {
        if(this.searchId == "") {
          const response = await http.post("/getStudents", {
            pageIndex: this.pageIndex,
            pageSize: this.pageSize
          });
          this.students = response.data || [];
          this.totalPages = response.total;
        } else {
          const response = await http.post("/getStudent", {
            id: this.searchId
          });
          if(response.id=="") {
            this.students = [];
            this.totalPages = 0;
          } else {
            this.students = [response] || [];
            this.totalPages = 1;
          }
          
        }
        
      } catch (error) {
        console.error("请求失败", error);
      }
    },
    handleAdd() {
      this.dialogTitle = "新增";
      this.form = { id: null, name: "", age: "", grade: "" };
      this.dialogVisible = true;
    },
    async handleEdit(row) {
      this.dialogTitle = "编辑";
      try {
        const response = await http.post(`/getStudent`, { id: row.id });
        if (response) {
          this.form = { ...response };
          this.dialogVisible = true;
        } else {
          this.$message({
            type: "error",
            message: "查询失败!",
          });
        }
      } catch (error) {
        console.error("请求失败", error);
        this.$message({
          type: "error",
          message: "查询失败!",
        });
      }
    },
    async handleDelete(row) {
      try {
        const response = await http.post(`/deleteStudent`, { id: row.id });
        if (response.result) {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.pageIndex = 1;
          this.fetchData();
        } else {
          this.$message({
            type: "error",
            message: "删除失败!",
          });
        }
      } catch (error) {
        console.error("请求失败", error);
        this.$message({
          type: "error",
          message: "删除失败!",
        });
      }
    },
    async handleSave() {
      try {
        var response;
        if (this.form.id === null) {
          // 新增
          response = await http.post("/saveStudent", this.form);
        } else {
          // 编辑
          response = await http.post(`/updateStudent`, this.form);
        }
        this.fetchData();
        this.dialogVisible = false;
        if (response.result || response.id!="") {
          this.$message({
            type: "success",
            message: "保存成功!",
          });
        } else {
          this.$message({
            type: "error",
            message: "保存  失败!",
          });
        }
        
      } catch (error) {
        console.error("请求失败", error);
        this.$message({
          type: "error",
          message: "保存失败!",
        });
      }
    },
  },
};
</script>

<style scoped>
.page-container {
  width: 100%;
  height: 100%;
}
.top-btns {
  text-align: right;
}
.el-button {
  margin-bottom: 10px;
}
.el-pagination {
  text-align: right;
  margin-top: 10px;
}
</style>
